package com.ywb.payment.controller;

import com.ywb.common.entity.*;
import com.ywb.payment.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;


/**
 * @Author ywb
 */
@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping
    public Result savePayment(Payment payment){
        if(paymentService.save(payment) == false){
            return Result.error();
        }
        return Result.success().setMessage(serverPort);
    }

    @GetMapping("/{id}")
    public Result getPayment(@PathVariable Long id){
        Payment payment = paymentService.getOne(id);
        if(payment == null){
            return Result.error("数据库查询失败");
        }
        return Result.success("payment", payment).setMessage(serverPort);
    }

    @GetMapping("/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();

        services.stream().forEach(log::info);

        List<ServiceInstance> instances = discoveryClient.getInstances("payment-com.ywb.payment.service");
        instances.stream().forEach(serviceInstance -> log.info(serviceInstance.getInstanceId() + "\t" + serviceInstance.getUri()));

        return services;
    }
    @GetMapping("/lb")
    public String mylb(){
        return serverPort;
    }
}
